import { Emitter } from '@/ts/base/common';
import { kernel, schema, model } from '@/ts/base';

class ViewProvider extends Emitter {
  private static instance: ViewProvider | undefined;
  activityList: any[] = [];
  private finished: boolean = false;
  metadata: schema.XEntity;
  private belongId: string;
  private publicBannerCollName = 'public-read-banner';
  private publicActivityCollName = 'public-read-activity';

  private constructor(metadata: schema.XEntity) {
    super();
    this.metadata = metadata;
    this.belongId = metadata.belongId;
  }

  public static resetInstance(): void {
    ViewProvider.instance = undefined;
  }

  public static getInstance(metadata?: schema.XEntity): ViewProvider | null {
    if (!ViewProvider.instance) {
      if (!metadata) {
        return null;
      }
      ViewProvider.instance = new ViewProvider(metadata);
    }
    return ViewProvider.instance;
  }

  /**
   * 加载公开banner
   */
  async loadBanner(): Promise<{
    workBench: model.FileItemShare[];
    activity: model.FileItemShare[];
    webSite: model.FileItemShare[];
  }> {
    if (this.finished) return { workBench: [], activity: [], webSite: [] };

    const data: any = await kernel.collectionLoad<any>(
      this.belongId,
      this.belongId,
      [],
      this.publicBannerCollName,
      {
        take: 1,
        options: {
          match: {
            isDeleted: false,
          },
          sort: {
            createTime: -1,
          },
        },
      },
    );
    const result = {
      workBench: data.data.flatMap((item: any) => item.workbench),
      activity: data.data.flatMap((item: any) => item.activity),
      webSite: data.data.flatMap((item: any) => item.webSite),
    };
    return result;
  }

  /**
   * 加载公开动态数据
   * @param take 请求条数
   */
  async load(take: number = 10): Promise<any[]> {
    if (this.finished) return [];

    const res: any = await kernel.collectionLoad<any[]>(
      this.belongId,
      this.belongId,
      [],
      this.publicActivityCollName,
      {
        skip: this.activityList.length,
        take: take,
        options: {
          match: {
            isDeleted: false,
          },
          sort: {
            createTime: -1,
          },
        },
      },
    );
    if (!res || !res.data || res.data.length === 0) {
      this.finished = true;
      return [];
    }

    const messages = res.data.map((item: any) => ({
      ...item,
      metadata: { ...item },
    }));
    this.finished = messages.length < take;
    this.activityList.push(...messages);
    return messages;
  }

  /**
   * 获取已加载的动态列表
   */
  get list(): any[] {
    return this.activityList;
  }
  get metdata(): {
    metadata: schema.XEntity;
  } {
    return {
      metadata: this.metadata,
    };
  }

  /**
   * 是否还有更多数据可加载
   */
  get hasMore(): boolean {
    return !this.finished;
  }
}

export default ViewProvider;
